<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <TreeSelect v-model="menuFilterSelectValue" placeholder="上级" style="width:200px" filterable clearable defaultExpandAll :expand-on-click-node="false"
        :data="menuTreeData"
        :props = "{ value: 'id',label: 'name',children: 'children' }"
        @change = "handleMenuFilterSelectChange($event)"/>
      <el-select v-model="listQuery.isActive" placeholder="是否启用" clearable class="filter-item" style="width: 130px">
        <el-option :key="true" :label="'是'" :value="true" />
        <el-option :key="false" :label="'否'" :value="false" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-if="buttons.create" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-if="buttons.export" v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" sortable="custom" align="left" :class-name="getSortClass('name')">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编码" prop="code" sortable="custom" align="left" :class-name="getSortClass('code')">
        <template slot-scope="{row}">
          <span>{{ row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" prop="type" sortable="custom" align="left" :class-name="getSortClass('type')">
        <template slot-scope="{row}">
          <el-tag :type="row.type | menuTypeCssFilter">{{ row.type | menuTypeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="权限" prop="permission" align="left">
        <template slot-scope="{row}">
          <el-tag>{{ row.permission }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="路由" prop="route" align="left">
        <template slot-scope="{row}">
          <span>{{ row.route }}</span>
        </template>
      </el-table-column>
      <el-table-column label="路径" prop="path" align="left">
        <template slot-scope="{row}">
          <span>{{ row.path }}</span>
        </template>
      </el-table-column>
      <el-table-column label="扩展" prop="extensions" align="left">
        <template slot-scope="{row}">
          <span>{{ row.extensions }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上级" prop="parentId" align="center" width="150px">
        <template slot-scope="{row}">
          <el-tag>{{ row.parentId | menuFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" prop="enabled" sortable="custom" align="center" width="120px" :class-name="getSortClass('enabled')">
        <template slot-scope="{row}">
          <el-tag :type="row.enabled ? 'success' : 'danger'">
            {{ row.enabled ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button v-if="buttons.update" type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button v-if="buttons.delete" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageIndex" :limit.sync="listQuery.pageSize" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="temp.type">
            <el-radio-button v-for="item in menuTypeOptions" :key="item.value" :label="item.value" :value="item.value">
              {{item.key}}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限" prop="permission">
          <el-input v-model="temp.permission" />
        </el-form-item>
        <el-form-item label="路由" prop="route">
          <el-input v-model="temp.route" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="temp.path" />
        </el-form-item>
        <el-form-item label="扩展" prop="extensions">
          <el-input v-model="temp.extensions" :autosize="{ minRows: 4, maxRows: 8}" type="textarea" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="上级" prop="parentId">
          <TreeSelect v-model="temp.parentId" placeholder="上级" filterable clearable defaultExpandAll :expand-on-click-node="false"
            :data="menuTreeData"
            :props = "{ value: 'id',label: 'name',children: 'children' }"/>
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-switch v-model="temp.enabled" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Create, Update, Delete, Get, GetPagedList, GetTree } from '@/api/menu'
import { GetUserMenuList } from '@/api/auth'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import TreeSelect from '@/components/TreeSelect'
let that
export default {
  name: 'Product',
  components: { Pagination,TreeSelect },
  directives: { waves },
  filters: {
    menuTypeFilter(id) {
      return that.menuTypeOptions.find(item => item.value == id)?.key
    },
    menuTypeCssFilter(id) {
      return that.menuTypeOptions.find(item => item.value == id)?.type
    },
    menuFilter(id) {
      return that.menuListData.find(item => item.id == id)?.name ?? '无'
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      buttons:{
        create:false,
        update:false,
        delete:false,
        detail:false,
        export:true
      },
      menuTypeOptions:[
        {key:'模块',value:0,type:""},
        {key:'页面',value:1,type:"success"},
        {key:'按钮',value:2,type:"danger"}
      ],
      menuTreeData: null,
      menuListData: [],
      menuFilterSelectValue:null,
      downloadLoading: false,
      pvData: [],
      dialogPvVisible: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      rules: {
        name: [{ required: true, message: '名称必填', trigger: 'change' }],
        type: [{ required: true, message: '类型必选', trigger: 'change' }],
        permission: [{ required: true, message: '权限必填', trigger: 'change' }]
      },
      temp: {
        id: undefined,
        name: null,
        type: null,
        permission: null,
        route: null,
        path: null,
        extensions: null,
        parentId: null,
        enabled: false
      },
      listQuery: {
        pageIndex: 1,
        pageSize: 100,
        sorting: null,
        id: null,
        name: null,
        type: null,
        parentIds: null,
        enabled: null
      },
      pagedList: {
        pageIndex: 1,
        pageSize: 10,
        totalCount: 0,
        items: null
      },
      defaultProps:{
        value: 'id',
        label: 'name',
        children: 'children',
      }
    }
  },
  beforeCreate () {
	  that = this
  },
  created() {
    this.getButtonPermissions()
    this.getMenuTree()
    this.getList()
  },
  methods: {
    getButtonPermissions(){
      GetUserMenuList().then(response => {
        if(response.data){
          let menus = response.data.filter(item=>item.parentId==this.$route.meta.parentId && item.type==2)
          this.buttons = {
            create:menus.some(item=>item.permission.includes(".Create")),
            update:menus.some(item=>item.permission.includes(".Update")),
            delete:menus.some(item=>item.permission.includes(".Delete")),
            detail:menus.some(item=>item.permission.includes(".Detail")),
            export:menus.some(item=>item.permission.includes(".Export"))
          }
        }
      })
    },
    getMenuTree() {
      GetTree().then(response => {
        let data = response.data.children
        if(data){ 
          this.menuTreeData = data
          this.menuListData = this.treeToList(this.menuTreeData,"children") 
        }
      })
    },
    getList() {
      this.listLoading = true
      GetPagedList(this.listQuery).then(response => {
        this.pagedList = response.data;
        this.list = this.pagedList.items
        this.total = this.pagedList.totalCount
        setTimeout(() => {
          this.listLoading = false
        }, 500)
      })
    },
    handleFilter() {
      this.listQuery.pageIndex = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: null,
        type: null,
        permission: null,
        route: null,
        path: null,
        extensions: null,
        parentId: null,
        enabled: false
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          Create(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.handleFilter()
          })
        }
      })
    },
    handleUpdate(row) {
      this.listLoading = true
      Get({id:row.id}).then(response => {
        Object.keys(this.temp).forEach((key) => {
          this.temp[key] = response.data[key]
        })
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          Update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.handleFilter()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.listLoading = true
      Delete({id:row.id}).then(response => {
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
        this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.handleFilter()
      })
    },
    sortChange(data) {
      const { prop, order } = data 
      if(prop && order){
        this.listQuery.sorting = prop + (order === 'ascending' ? ' ascending' : ' descending')
      }
      else {
        this.listQuery.sorting = null
      }
      this.handleFilter()
    },
    getSortClass: function(key) {
      if(this.listQuery.sorting){
        const items = this.listQuery.sorting.split(' ')
        if(items[0] == key){
          return items[1]
        }
      }
      return null
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '名称', '编码','类型', '权限', '路由','路径', '上级', '是否可用']
        const filterVal = ['id', 'name', 'code', 'type', 'permission', 'route', 'path','parentId', 'enabled']
        const data = this.list.map(v => filterVal.map(j => {
          if (j === 'type') {
            return this.menuTypeOptions.find(item => item.value == v[j])?.key
          }
          if (j === 'parentId') {
            return this.menuListData.find(item => item.id == v[j])?.name
          }
          else if (j === 'enabled') {
            return v[j] === true ? '是' : '否'
          }
          else {
            return v[j]
          }
        }))
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'menu-list'
        })
        this.downloadLoading = false
      })
    }, 
    handleMenuFilterSelectChange(data){
      this.listQuery.parentIds = null
      if(data){ 
        // 多选
        if(data.multiple){
          if(this.categoryFilterSelectValue){
            this.listQuery.parentIds = this.categoryFilterSelectValue.join(',')
          }
        }else{
          if(data.data){ 
            let values = data.id
            if(data.children){
              let dataArray = []
              dataArray.push(data.data)
              let items = this.treeToList(dataArray,"children")
              if(items){
                values = items.map((item,index)=>{
                  return item.id
                }).join(',')
              }
            }
            this.listQuery.parentIds = values
          }
        }
      }
    },
     
    treeToList(arrs,childs,attrArr){
      let attrList = []
      if(!Array.isArray(arrs) && !arrs.length) {
        return []
      }
      if(typeof childs !== 'string') {
        return []
      }
      if(!Array.isArray(attrArr) || Array.isArray(attrArr) && !attrArr.length) {
        attrList = Object.keys(arrs[0])
        attrList.splice(attrList.indexOf(childs), 1)
      }
      else{
        attrList = attrArr;
      }
      let list = []
      const getObj = (arr)=> {
        arr.forEach(row => {
          let obj = {}
          attrList.forEach(item=> {
            obj[item] = row[item];
          })
          list.push(obj)
          if(row[childs]){
            getObj(row[childs])
          }
        })
        return list
      }
      return getObj(arrs)
    }
  }
}
</script>
